import TileLayer from "ol/layer/Tile";
import TileGrid from 'ol/tilegrid/TileGrid';
import WMTS from "ol/source/WMTS"; // eslint-disable-line
import ImageWMS from 'ol/source/ImageWMS.js'
import TileArcGISRest from "ol/source/TileArcGISRest";
import VectorSource from "ol/source/Vector";
import ImageStatic from "ol/source/ImageStatic";
import VectorLayer from "ol/layer/Vector";
import ImageLayer from "ol/layer/Image";
import LayerGroup from "ol/layer/Group";
import XYZ from "ol/source/XYZ";
// import Cluster from "ol/source/Cluster";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import { Fill, Stroke, Style, Circle as circleStyle } from "ol/style";
import { get as getProjection } from "ol/proj";
import { getTopLeft, getWidth } from "ol/extent";
import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import Point from "ol/geom/Point";
// import GeoJSON from "ol/format/GeoJSON";
import Icon from "ol/style/Icon";
import Text from "ol/style/Text";
// import Overlay from "ol/Overlay";
import { fromExtent } from "ol/geom/Polygon";
import { LinearRing, MultiPolygon } from "ol/geom";
import { register } from 'ol/proj/proj4';
import proj4 from 'proj4';
import { transform, useGeographic, Projection, addProjection } from "ol/proj";

// import { Select } from "ol/interaction";
// import { click } from "ol/events/condition";
//turf
// import * as turf from "@turf/turf";
import GeoJSON from 'ol/format/GeoJSON';

import { targetNotEditable } from "ol/events/condition";
function Layer(map) {
  this.map = map;
}

//样式函数stroke fill
let styleFunction = function (styleObj) {
  let style = {};
  if (styleObj && (styleObj.strokeColor || styleObj.strokeWidth)) {
    style.stroke = new Stroke({
      color: styleObj.strokeColor || "#FFFFFF",
      width: styleObj.strokeWidth || 1,
    });
  }
  if (styleObj && styleObj.fillColor) {
    style.fill = new Fill({
      color: styleObj.fillColor || "rgba(255,255,255,0.5)",
    });
  }
  return new Style(style);
};
/**
 * @description: 添加json的边线图层
 * @param {*} jsonData json数据
 */
Layer.prototype.createAreaLineLayer = function (jsonData) {
  // 创建矢量数据源
  const vectorSource = new VectorSource({
    features: new GeoJSON().readFeatures(jsonData)
  });
  // 创建矢量图层并设置样式
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0)'//填充为空白（透明）
      }),
      stroke: new Stroke({
        color: 'black', // 边线颜色
        width: 2
      })
    })
  });
  let layer = this.createGroup("边界图层组", 4, [vectorLayer]);
  this.map.addLayer(layer);
}
/**
 * @description: 获取所有的图层
 * @return {*} 对应图层对象
 */
Layer.prototype.getAllLayers = function () {
  let layerArr = this.map.getLayers().array_;
  return layerArr;
};

/**
 * @description: 根据图层名获取图层
 * @param {string} layerName 图层名称
 * @return {*} 对应图层对象
 */
Layer.prototype.getLayerByName = function (layerName) {
  let layerArr = this.getAllLayers();
  for (let k = 0; k < layerArr.length; k++) {
    if (
      layerArr[k].values_.layerName == layerName ||
      layerArr[k].layerName == layerName
    ) {
      return layerArr[k];
    }
  }
};

/**
 * @description: 叠加WMTS
 * @param {string} layerName 图层名称
 * @param {string} url 图层路径
 * @param {object} params 参数
 * @return {TileLayer} 图层对象
 */
Layer.prototype.getTianDiTuWmtsLayerByParam = function (layerName, url, type) {
  const token = "fe40e8bfa4d16f7a68afafe70ad0483e";
  let m = parseInt(Math.random() * 8); //0-7随机选择
  const img =
    "http://t" +
    m +
    ".tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk="; //影像底图
  const cia =
    "http://t" +
    m +
    ".tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk="; //影像注记
  const vec =
    "http://t" +
    m +
    ".tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk="; //影像底图
  const cva =
    "http://t" +
    m +
    ".tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk="; //影像注记
  const ter =
    "http://t" +
    m +
    ".tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk="; //地形晕渲
  const cta =
    "http://t" +
    m +
    ".tianditu.gov.cn/cta_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk="; //地形注记
  if (!url) return null;
  url = decodeURIComponent(url);
  const projection = getProjection("EPSG:3857");
  const projectionExtent = projection.getExtent();
  const size = getWidth(projectionExtent) / 256;
  const resolutions1 = new Array(19);
  const resolutions = new Array(19);
  const matrixIds = new Array(19);
  for (let z = 0; z < 20; ++z) {
    //1.40625
    resolutions[z] = size / Math.pow(2, z); //天地图经纬 度底图的计算参数
    resolutions1[z] = 1.40625285 / Math.pow(2, z); //苍穹 底图计算参数（可能需要修改，根据点位偏移自己去调整）
    matrixIds[z] = z;
  }
  let source = new WMTS({
    name: layerName,
    url: url,
    layer: type,
    style: "default",
    matrixSet: "w",
    format: "tiles",
    wrapX: true,
    tileGrid: new WMTSTileGrid({
      origin: getTopLeft(projectionExtent), //resolutions: res.slice(0, 15),
      resolutions: resolutions,
      matrixIds: matrixIds,
    }),
    crossOrigin: 'anonymous',
  });
  source.setTileUrlFunction(function (data) {
    let tilematrix = data[0];
    let tilecol = data[1];
    let tilerow = data[2];
    let baseUrl = "";
    if (type == "img") baseUrl = img;
    if (type == "cia") baseUrl = cia;
    if (type == "vec") baseUrl = vec;
    if (type == "cva") baseUrl = cva;
    if (type == "ter") baseUrl = ter;
    if (type == "cta") baseUrl = cta;
    return (
      baseUrl +
      token +
      `&TILEMATRIX=${tilematrix}&TILECOL=${tilecol}&TILEROW=${tilerow}`
    );
  });
  let layer = new TileLayer({
    source: source,
  });
  // this.map.addLayer(layer);
  return layer;

};

/**
 * @description: 添加arcgis瓦片服务图层
 * @param {string} layerName 图层路径名称
 * @param {string} url 图层路径
 * @return {TileLayer} 图层对象
 */
Layer.prototype.getArcgisMapServer = function (layerName, url) {
  if (url) {
    const arcLayer = new TileLayer({
      source: new TileArcGISRest({
        wrapX: false,
        url: url,
      }),
    });
    if (layerName) {
      arcLayer.set("layerName", layerName);
    }
    return arcLayer;
  }
};


Layer.prototype.setWmsLayer = function (layers, layername) {
  let imageLayer = new ImageLayer({
    zIndex: 99999999,
    source: new ImageWMS({

      ratio: 1,
      url: ' http://localhost:8090/geoserver/TapWater/wms',
      params: {
        //service: 'WMS',
        VERSION: '1.1.0',
        request: 'GetMap',
        LAYERS: layers,
        STYLES: '',
        FORMAT: 'image/png', //通常使用 image/png 格式   
      },
      // crossOrigin: 'anonymous',
    }),
    name: `Layer${layername}`,
    opacity: 1,

  });
  imageLayer.set("layerName", `Layer${layername}`);
  ;
  this.map.addLayer(imageLayer);
};

/**
 * @description: 行政区遮罩（带洞多边形）
 * @param {*} layer 遮罩图层
 * @param {*} holeGeom 行政区多边形
 * @param {*} styleObj 遮罩样式
 * @return {*}
 */
Layer.prototype.addPolygonHoles = function (layer, holeGeom, styleObj = {}) {
  let extent = [-180, -90, 180, 90];
  let polygonRing = fromExtent(extent); //从范围创建多边形
  let coords = holeGeom.getCoordinates(); //获取此几何的坐标数组。该数组具有用于多边形的GeoJSON坐标数组的结构
  if (holeGeom instanceof MultiPolygon)
    coords.forEach((coord) => {
      let linearRing = new LinearRing(coord[0]);
      polygonRing.appendLinearRing(linearRing); //将传递的线环添加到这个多边形
    });
  else {
    let linearRing = new LinearRing(coords[0]);
    polygonRing.appendLinearRing(linearRing); //将传递的线环添加到这个多边形
  }
  let feature = new Feature({ geometry: polygonRing });
  feature.setStyle(styleFunction(styleObj));
  layer.getSource().addFeature(feature);
};

/**
 * @description: 添加一个矢量遮罩图层
 * @param {*} layerName 图层名
 * @param {*} zIndex 图层
 * @return {*} vectorLayer
 */
Layer.prototype.createMaskLayer = function (layerName, zIndex) {
  let vectorLayer = new VectorLayer({
    source: new VectorSource(),
    zIndex: zIndex || 10,
    declutter: false, //防止标注文字重复标注
    style: new Style({
      fill: new Fill({
        color: "rgba( 255, 255, 255, 0.7)",
      }),
      stroke: new Stroke({
        color: "#f4b49f",
        width: 3,
      }),
    }),
  });
  vectorLayer.set("layerName", layerName || "遮罩图层");
  this.map.addLayer(vectorLayer);
  return vectorLayer;
};

/**
 * @description: 添加json的边线图层
 * @param {*} jsonData json数据
 */
Layer.prototype.createAreaLineLayer = function (jsonData) {
  // 创建矢量数据源
  const vectorSource = new VectorSource({
    features: new GeoJSON().readFeatures(jsonData)
  });
  let data = new GeoJSON().readFeatures(jsonData);
  ;
  // 创建矢量图层并设置样式
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0)'//填充为空白（透明）
      }),
      stroke: new Stroke({
        color: 'blue', // 边线颜色
        width: 2
      })
    }),
    zIndex: 11
  });
  let layer = this.createGroup("边界图层组", 4, [vectorLayer]);
  this.map.addLayer(layer);
}

//创建点符号图层
Layer.prototype.createVectorLayer = function (layerName, styleObj, zIndex, sourceObj, declutter) {
  let _sourceObj = sourceObj == null ? { wrapX: false } : sourceObj
  let source = new VectorSource(_sourceObj);
  let vectorLayer = new VectorLayer({
    source: source,
    zIndex: zIndex || 15,
    declutter: declutter || false, //防止标注文字重复标注
    style: styleFunction(styleObj)
  });
  vectorLayer.set('layerName', layerName);
  this.map.addLayer(vectorLayer);
  return vectorLayer;
}

/**
 * @description: 创建一个图层组
 * @param {*} LayerGroupName 图层组名称
 * @param {*} zIndex 图层顺序
 * @param {*} layers 图层数组 []
 * @return {*} layerGroup
 */
Layer.prototype.createGroup = function (layerGroupName, zIndex, layers) {
  let layerGroup = new LayerGroup({
    layers: layers,
    zIndex: zIndex || 0,
  });
  layerGroup.set("layerName", layerGroupName || "图层组");
  return layerGroup;
};

/**
 * @description: 初始化图层，影像与矢量
 * @param {*} geom geometry对象
 */
Layer.prototype.initLayer = function () {
  // localStorage.setItem("xzqhGeom", JSON.stringify(geom.getCoordinates()[0]));
  // //------------添加影像 全国影像 + arcgis影像
  // let img = this.getTianDiTuWmtsLayerByParam("天地图影像", "img", "img");
  // let cia = this.getTianDiTuWmtsLayerByParam("天地图影像注记", "cia", "cia");
  // let imgLayerGroup = this.createGroup("影像图层组", 1, [img, cia]);


  // //------------添加矢量 全国矢量 + arcgis矢量
  // let vec = this.getTianDiTuWmtsLayerByParam("天地图矢量", "vec", "vec");
  // let cva = this.getTianDiTuWmtsLayerByParam("天地图矢量注记", "cva", "cva");
  // let vecLayerGroup = this.createGroup("矢量图层组", 2, [vec]);
  // let cvaLayerGroup = this.createGroup("矢量图层组", 3, [cva]);
  // cvaLayerGroup.setVisible(false);
  // vecLayerGroup.setVisible(false);
  // //------------添加地形
  // let ter = this.getTianDiTuWmtsLayerByParam("天地图地形", "ter", "ter");
  // let cta = this.getTianDiTuWmtsLayerByParam("天地图影像注记", "cta", "cta");
  // let terLayerGroup = this.createGroup("地形图层组", 1, [ter, cta]);
  // terLayerGroup.setVisible(false);
  // this.map.addLayer(vecLayerGroup); //添加矢量
  // this.map.addLayer(cvaLayerGroup); //添加矢量

  //-------------添加地图遮罩，并将地图放大到geom范围
  // let boundaryLayer = this.createMaskLayer("行政区域遮罩图层"); //zindex为10
  // boundaryLayer.getSource().clear();
  // let extent = geom.getExtent();
  // this.fitExtentPaddingLayout(extent);
  // this.addPolygonHoles(boundaryLayer, geom, {
  //     strokeColor: "white",
  //     strokeWidth: 2,
  //     fillColor: "rgba(0,0,0,0.4)",
  // });
  //设置行政区划边界，之后用于重置地图
  // localStorage.setItem("xzqhExtent", JSON.stringify(extent));
  //返回所有图层与行政区范围
  //-------------添加本地DMGIS地图瓦片
  // this.getTileMapByUrl("/layerData/tileMap", "矢量地图瓦片", [265702.134038, 604437.605838, 408466.508310, 747201.980111], 0)
  this.getTileMapByUrl("/layerData/imgMap", "影像地图瓦片", [302702.289221, 646114.233632, 322729.977849, 666141.922260], 1).setVisible(false)
  this.getTileMapByUrl("/layerData/piplineAndNet", "管网数据", [307268.865000, 649611.550637, 319697.339000, 662040.024637], 2)


  //添加Arcgis地图
  this.getBaseMapByArcgis("/SpaceTimeBigData_SZSDZDT_Light_SZ2000_20230913", "矢量地图瓦片", null, 1, 'sz2000', 'xW5CT12-orzuhh0dBQZanMOvaX9mj8XPfPCFDOQbO15fg-2xP0l17A09Bk_QmePlBEdzfJ_4fH7YBVTUXJRRDBmkdjPpud1VxVMNcv2hbCpYp3pxBfTp3XHTRjD09bequbXZJwawzxcajr2GsrtT_g..')
  return {
    layer: this.map.getLayers().getArray(),
  };
};
//一般瓦片
Layer.prototype.getTileMapByUrlNormal = function (url, layername, extent, zindex, proj) {
  const projection = getProjection(proj);
  let resolutions = [];
  let minx = extent[0];
  let maxx = extent[2];
  let miny = extent[1];
  let maxy = extent[3];
  let newExtent = [minx, miny, maxx, maxy]
  let maxZoom = 18;
  let tileSize = 256;
  let layer = new TileLayer({
    source: new XYZ({     // 使用XYZ方式加载瓦片地图
      // projection: projection,
      projection: "sz2000",
      // projection:"EPSG:3857",
      crossOrigin: "anonymous",//解决跨域问题，避免截图产生空白问题
      axisOrientation: 'enu',
      cacheSize: 1024, // 缓存大小，单位为瓦片数目
      preload: 4, // 预加载4级瓦片
    }),
    zIndex: zindex,
    wrapX: true,
  })
  layer.set("layerName", layername);
  setTimeout(() => { this.map.addLayer(layer); }, 1000)
  return layer;
}
//Arcgis服务地图
Layer.prototype.getBaseMapByArcgis = async function (url, layername, extent, zindex, proj, token) {
  //请求arcgis 服务
  let arcgisUrl = process.env.VUE_APP_BASE_API + "/arcgis"+'/OneMapServer/rest/services'+ url + '/MapServer';
  let newExtent = [];
  let orgin = {};
  let resData = null;
  await fetch(arcgisUrl + '?f=json' + '&token=' + token).then(res => {
    return res.json()
  }).then(data => {
    resData = data
  })
  newExtent = [resData.fullExtent.xmin, resData.fullExtent.ymin, resData.fullExtent.xmax, resData.fullExtent.ymax]
  // let source = new TileArcGISRest({
  //   url: arcgisUrl + "/tile" + "/{z}/{x}/{y}" + "?blankTile=false" + '&token=' + token,
  // });
  orgin = { x: resData.tileInfo.origin.x, y: resData.tileInfo.origin.y };
  let resolutions = resData.tileInfo.lods.map((item) => {
    return item["resolution"];
  });
  console.log(newExtent, orgin, "arcgis底图参数");
  let tilegrid = new TileGrid({
    origin: [orgin.x, orgin.y], // 设置原点坐标
    resolutions: resolutions, // 设置分辨率
    tileSize: 256,
    extent: newExtent
  });
  let source = new XYZ({
    projection: "sz2000",
    crossOrigin: "anonymous",//解决跨域问题，避免截图产生空白问题
    axisOrientation: 'enu',
    tileGrid: tilegrid,
    cacheSize: 1024, // 缓存大小，单位为瓦片数目
    preload: 4, // 预加载4级瓦片
    url: arcgisUrl + "/tile" + "/{z}/{y}/{x}" + "?blankTile=false" + '&token=' + token,
  });
  // 创建图层
  let layer = new TileLayer({
    source: source,
    layerName: layername,
    zIndex: zindex,
    wrapX: true
  });
  setTimeout(() => { this.map.addLayer(layer); }, 100)
}
//DMGIS平台瓦片
Layer.prototype.getTileMapByUrl = function (url, layername, extent, zindex, proj) {
  const projection = getProjection(proj);
  let resolutions = [];
  let minx = extent[0];
  let maxx = extent[2];
  let miny = extent[1];
  let maxy = extent[3];
  let newExtent = [minx, miny, maxx, maxy]
  let maxZoom = 18;
  let tileSize = 256;
  for (let i = 0; i <= maxZoom; i++) {
    resolutions[i] = (maxx - minx) / Math.pow(2, i) / tileSize;
  }
  // console.log(resolutions, "分辨率");

  let tilegrid = new TileGrid({
    origin: [minx, maxy], // 设置原点坐标
    resolutions: resolutions, // 设置分辨率
    tileSize: tileSize,
    minZoom: 0,
    maxZoom: maxZoom,
    extent: newExtent
  });
  let layer = new TileLayer({
    source: new XYZ({     // 使用XYZ方式加载瓦片地图
      // projection: projection,
      projection: "sz2000",
      // projection:"EPSG:3857",
      tileGrid: tilegrid,
      crossOrigin: "anonymous",//解决跨域问题，避免截图产生空白问题
      axisOrientation: 'enu',
      cacheSize: 1024, // 缓存大小，单位为瓦片数目
      preload: 4, // 预加载4级瓦片
      tileUrlFunction: function (tileCoord) {
        let z = tileCoord[0];
        // let y = tileCoord[2]
        let y1 = Math.pow(2, z) - 2 - (Math.abs(tileCoord[2]) - 1);
        let x = tileCoord[1];
        let imgUrl = process.env.VUE_APP_BASE_API + "/mapTile" + url + "/{z}/{y}/{x}.png";
        return imgUrl.replace("{z}", z).replace("{x}", x).replace("{y}", y1);
      },
    }),
    zIndex: zindex,
    wrapX: true
  });
  layer.set("layerName", layername);
  setTimeout(() => { this.map.addLayer(layer); }, 100)
  return layer;
};
Layer.prototype.addFeatureByGeom = function (features, zIndex, styleObj) {
  // 创建矢量图层
  let vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: features
    }),
    style: styleFunction(styleObj),
    zIndex: zIndex
  });
  this.map.addLayer(vectorLayer)
}
//图片图层
Layer.prototype.setImgLayer = function (url, extent, layername) {
  if (url) {
    let imageLayer = new ImageLayer({
      zIndex: 2,
      name: `Layer${layername}`,
      opacity: 0.6,
    });
    // 更新图片图层的源
    imageLayer.setSource(
      new ImageStatic({
        url: url,
        imageExtent: extent,
      })
    );
    imageLayer.set("layerName", "静态图片图层");
    this.map.addLayer(imageLayer);
  }
};
//消除图片图层
Layer.prototype.clearImgLayer = function (layername) {
  let layer = {}
  // ;
  // 找到Layer图层并清除
  if (layername) {
    layer = this.map.getLayers().getArray().find(layer => layer.get('name') === `Layer${layername}`);
    // ;
  }
  // 移除图层
  if (layer) {
    this.map.removeLayer(layer);
  }
}

//添加Feature到图层中
Layer.prototype.addPolygonsToLayer = function (layer, polygons, style) {

  if (layer) {
    let features = [];
    polygons.forEach((item, index) => {
      if (item) {
        let feature = new Feature({
          geometry: new Polygon([item]),
        });
        // 创建样式函数
        let styleFunc = function () {
          return new Style({
            fill: new Fill({
              color: style.fill,
            }),
            stroke: new Stroke({
              color: style.strokeColor || "#FFFFFF",
              width: style.strokeWidth || 1,
            })
          });
        };
        // 设置要素的样式
        feature.setStyle(styleFunc);
        // feature.type = "预警区裁剪";
        feature.index = index;
        features.push(feature);
      }
    });
    // 将要素添加到矢量图层
    layer.getSource().addFeatures(features);
    return features
  } else {
    return null
  }
}

//添加预警区
Layer.prototype.addGridArea = function (polygons) {
  ;
  let features = [];
  polygons.forEach((item, index) => {
    if (item) {
      let points = item.points;
      let feature = new Feature({
        geometry: new Polygon([points]),
        //标注信息
        // markerInfo: markerInfo||''
      });
      // 创建样式函数
      let styleFunc = function () {
        if (item.level == "0") {
          return new Style({
            fill: new Fill({
              color: "yellow",
            }),
          });
        } else if (item.level == "1") {
          return new Style({
            fill: new Fill({
              color: "orange",
            }),
          });
        }
        else if (item.level == "2") {
          return new Style({
            fill: new Fill({
              color: "red",
            }),
          });
        }
      };
      // 设置要素的样式
      feature.setStyle(styleFunc);
      feature.setProperties(item);
      feature.type = "预警区";
      feature.index = index;
      features.push(feature);
    }
  });
  let layer = this.getLayerByName("qxfxyjLayer");
  //先清空图层
  layer.getSource().clear();
  // 将要素添加到矢量图层
  layer.getSource().addFeatures(features);
  let extent = layer.getSource().getExtent();
  extent[0] != Infinity &&
    this.fitExtentPadding(extent, [150, 150, 150, 100], 1000);
}

/**
* @description: 添加隐患点
* @param {*} geom geometry对象
*/
Layer.prototype.addYhdPoint = function (pointsdata, countData) {
  let features = [];
  let countDataFeatures = [];
  // let colorfeaturesR = [];
  // let colorfeaturesO = [];
  // let colorfeaturesY = [];
  // let colorfeaturesB = [];
  //隐患点
  ;
  pointsdata.forEach((points) => {
    points.data.forEach((item, index) => {
      if (item?.lon && item?.lat) {
        // 创建点几何体
        let point = new Point([Number(item.lon), Number(item.lat)]); // x和y分别是点的经度和纬度
        // 创建点要素
        let feature = new Feature(point);
        // 创建样式函数
        let styleFunc = function () {
          return new Style({
            image: new Icon({
              // src: require("@/assets/images/fxgl/zhd/" + item.zhdtype + ".png"),
              scale: 0.7,
            }),
          });
        };

        // 设置要素的样式
        feature.setStyle(styleFunc);
        feature.setProperties(item);
        feature.type = points.yhdtype;
        feature.index = index;
        features.push(feature);
      }
    });
  })
  //区县隐患点统计
  countData.forEach((points) => {
    // 创建点几何体
    let point = new Point([Number(points.lon), Number(points.lat)]); // x和y分别是点的经度和纬度
    // 创建点要素
    let feature = new Feature(point);
    // 设置样式函数
    let styleFunc = function () {
      return new Style({
        image: new Icon({
          // src: require("@/assets/images/fxgl/zhd/markerCount.png"),
          scale: 0.6,
        }),
        text: new Text({
          font: "bold 20px sans-serif",
          text: points.adname + "\n" + points.value,
          fill: new Fill({
            color: "#fff",
          }),
          offsetY: -5, // 偏移量，使文本位于点的上方
        }),
      });
    };

    // 设置要素的样式
    feature.setStyle(styleFunc);
    countDataFeatures.push(feature);

  })
  // const source = new VectorSource({
  //   features,
  // });
  // const clusterSource = new Cluster({
  //   distance: 200, // 聚合点与点之间的距离
  //   // minDistance: 200, // 聚合点与点之间的最小距离
  //   source: source,
  // });
  const countDataSource = new VectorSource({
    features: countDataFeatures,
  });
  const style = function (feature) {
    // 点的个数
    const size = feature.get("features").length;
    // ;
    return new Style({
      image: new circleStyle({
        // 圆形
        radius: 20, // 半径
        stroke: new Stroke({
          // 边框
          color: "#fff",
        }),
        fill: new Fill({
          // 填充
          color: "#3399CC",
        }),
      }),
      text: new Text({
        // 文字样式
        font: "15px sans-serif",
        text: size.toString(),
        fill: new Fill({
          color: "#fff",
        }),
      }),
    });
  };

  let layer = this.getLayerByName("隐患点图层");
  // 先清空图层
  layer.getSource().clear();
  // layer.setSource(countDataSource);
  // layer.setSource(colorsource);
  layer.setStyle(style);
  // 将要素添加到矢量图层
  let extent = layer.getSource().getExtent();
  ;
  let defaultExtent = JSON.parse(localStorage.getItem("xzqhExtent"))
  extent[0] != Infinity ?
    this.fitExtentPadding(extent, [150, 150, 150, 100], 1000) : this.fitExtentPadding(defaultExtent, [150, 150, 50, 50], 1000);
  this.map.on("moveend", () => {
    const zoom = this.map.getView().getZoom(); //获取当前地图的缩放级别
    if (zoom >= 11) {
      layer.setSource(new VectorSource());
      layer.getSource().addFeatures(features);
    } else if (zoom >= 7 && zoom < 11) {
      layer.setSource(countDataSource);
    } else {
      layer.setSource(new VectorSource());
    }
  });
};
//添加面雨量多边形
Layer.prototype.addMylPolygon = function (polygons) {
  let features = [];
  let extents = [];
  polygons.forEach((item, index) => {
    if (item) {
      let points = item.basinPerimeterArray;
      let feature = new Feature({
        geometry: new Polygon(points),
        //标注信息
        // markerInfo: markerInfo||''
      });
      // 创建样式函数
      let styleFunc = function (feature) {
        return new Style({
          fill: new Fill({
            color: "pink",
          }),
        });
      };
      // 设置要素的样式
      feature.setStyle(styleFunc);
      feature.setProperties(item);
      feature.type = "面雨量";
      feature.index = index;
      features.push(feature);
      extents.push(feature.getGeometry().getExtent());
    }
  });
  let layer = this.getLayerByName("雨量图层");
  //先清空图层
  layer.getSource().clear();
  // 将要素添加到矢量图层
  layer.getSource().addFeatures(features);


};
/**
 * @description: 地图放大到某个区域
 * @param {*} extent 范围
 * @param {*} paddingList 边距
 * @return {*}
 */
Layer.prototype.fitExtentPadding = function (extent, paddingList, duration) {
  this.map.getView().fit(extent, {
    duration: duration || 0, // 动画持续时间（毫秒）
    padding: paddingList || [0, 0, 0, 0], // 可根据需要调整填充值
  });
};

//[100, 0, 20, 0]相对于布局的padding
Layer.prototype.fitExtentPaddingLayout = function (extent, duration) {
  this.fitExtentPadding(extent, [100, 0, 20, 0], duration);
};

Layer.prototype.fitFeature = function (feature, duration) {
  this.map.getView().fit(feature.getGeometry().getExtent(), {
    duration: duration || 0, // 动画持续时间（毫秒）
  });
};

Layer.prototype.fitSource = function (vectorSource, duration) {
  this.map.getView().fit(vectorSource.getExtent(), {
    duration: duration || 0, // 动画持续时间（毫秒）
  });
};

Layer.prototype.fitExtent = function (extent, duration) {
  ;
  this.map.getView().fit(extent, {
    duration: duration || 0, // 动画持续时间（毫秒）
  });
};
//预警分析
//行政区裁剪
Layer.prototype.cutsjyj = function (cutarea) {
  // ;
  // 找到addsjyjLayer图层并清除
  let layer = this.map.getLayers().getArray().find(layer => layer.get('layerName') === 'addsjyjLayer');
  // 移除图层
  if (layer) {
    this.map.removeLayer(layer);
  }
}
//添加网格点
Layer.prototype.addGridPoint = function (points, zIndex) {
  let features = [];
  let item = points;

  for (let i = 0; i < item.lon.length; i++) {

    if (item?.lon[i] && item?.lat[i]) {

      // 创建点几何体
      let point = new Point([item.lon[i], item.lat[i]]); // x和y分别是点的经度和纬度
      // 创建点要素
      let feature = new Feature(point);
      // 创建样式函数
      let styleFunc = function (feature) {
        return new Style({
          text: new Text({
            text: item.val[i],
            textAlign: "center", // 位置
            font: "bolder 10px 微软雅黑",
            fill: new Fill({
              color: "#333",
            }),
            // backgroundFill: new Fill({
            //     color: styleObj.backgroundFill || "#ffb663",
            // }),
            stroke: new Stroke({
              color: "#333",
              width: 0.5,
            }),
          })
        });
      };
      // 设置要素的样式
      feature.setStyle(styleFunc);
      feature.setProperties(item.val[i]);
      feature.type = "网格点";
      feature.index = i;
      features.push(feature);
    }
  }

  let layer = this.getLayerByName("qxfxyjLayer");
  //先清空图层
  layer.getSource().clear();
  // 将要素添加到矢量图层
  layer.getSource().addFeatures(features);
  let extent = layer.getSource().getExtent();
  extent[0] != Infinity &&
    this.fitExtentPadding(extent, [100, 450, 50, 50], 1000);
  this.map.on("moveend", (e) => {
    const zoom = this.map.getView().getZoom(); //获取当前地图的缩放级别
    if (zoom >= 12) {
      layer.setVisible(true);
    } else {
      layer.setVisible(false);
    }
  });
}
export default Layer;